package com.idp.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.idp.common.enums.MessageEnum;
import com.idp.common.error.SystemException;
import com.idp.common.model.PageModel;
import com.idp.app.dto.SySjzdDto;
import com.idp.app.dto.SySjzdSearchDto;
import com.idp.app.entity.SySjzdEntity;
import com.idp.app.mapper.SySjzdMapper;
import com.idp.app.service.SySjzdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据字典表Service实现类
 * @author Simon
 */
@Service("sySjzdService")
public class SySjzdServiceImpl implements SySjzdService {

	@Autowired
	private SySjzdMapper sySjzdMapper;

	@Override
	public PageModel<SySjzdDto> findByPage(SySjzdSearchDto sySjzdSearchDto) {

		PageModel<SySjzdDto> page = new PageModel<SySjzdDto>();

		page.setList(sySjzdMapper.getList(sySjzdSearchDto));

		return page;
	}

	@Override
	public SySjzdDto getById(String id) {

		if(ObjectUtil.isEmpty(id)) {
			throw new SystemException(MessageEnum.PARAM_ERROR);
		}

		SySjzdDto sySjzdDto = sySjzdMapper.getById(id);

		if(sySjzdDto == null) {
			throw new SystemException(MessageEnum.DATA_NOT_EXIST);
		}

		return sySjzdDto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(SySjzdDto sySjzdDto) {

		SySjzdEntity sySjzdEntity = BeanUtil.toBean(sySjzdDto, SySjzdEntity.class);

		sySjzdMapper.insert(sySjzdEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SySjzdDto sySjzdDto) {

		SySjzdEntity sySjzdEntity = sySjzdMapper.selectById(sySjzdDto.getId());

        if(sySjzdEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }
		CopyOptions copyOptions = new CopyOptions();
		copyOptions.setIgnoreNullValue(true);
		BeanUtil.copyProperties(sySjzdDto, sySjzdEntity, copyOptions);

		sySjzdMapper.updateById(sySjzdEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(String id) {

		SySjzdEntity sySjzdEntity = sySjzdMapper.selectById(id);

        if(sySjzdEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }

		sySjzdMapper.deleteById(id);
	}

}
